package com.imist.jdbcutil;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCUtil {
    private static final String DRIVER_CLASS ;
    private static final String URL;
    private static final String USERNAME ;
    private static final String PASSWORD ;

    static {
        Properties prop = new Properties();
        // 这里注意文件的路径，如果是IDE则放在Java目录下，eclipse放在src下，注意不用路径，因为发布之后的代码无法识别路径
        InputStream inputStream = JDBCUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
        try {
            prop.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //这里注意properties 的写法，键值对对应，文件里面值不需要加引号
        DRIVER_CLASS = prop.getProperty("DRIVER_CLASS");
        URL = prop.getProperty("URL");
        USERNAME = prop.getProperty("USERNAME");
        PASSWORD = prop.getProperty("PASSWORD");
//        DRIVER_CLASS = "com.mysql.cj.jdbc.Driver";
//        URL = "jdbc:mysql://localhost:3306/jdbc_test?useSSL=false&characterEncoding=UTF-8";
//        USERNAME = "root";
//        PASSWORD = "123456";
    }

    private static void loadDriver() throws ClassNotFoundException {
        Class.forName(DRIVER_CLASS);
    }

    public static Connection getConnection() throws Exception {
        loadDriver();
        Connection connection = DriverManager.getConnection(URL,USERNAME,PASSWORD);
        return connection;
    }

    public static void release(Connection connection,Statement statement){

        if (statement != null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            statement = null;
        }
        if (connection != null){
            try {
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            connection = null;
        }
    }
    public static void release(Connection connection, Statement statement, ResultSet resultSet){
        if (resultSet != null){
            try {
                resultSet.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            resultSet = null;
        }
       release(connection,statement);
    }
}
